import tkinter as tk
from PIL import Image, ImageTk
from tkinter import filedialog
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def load_image():
    global img
    filepath = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.jpeg *.png")])
    if not filepath:
        return
    img = Image.open(filepath)
    max_size = 400
    if img.size[0] > max_size or img.size[1] > max_size:
        img.thumbnail((max_size, max_size))
    update_image()

def update_image():
    global img, img_tk, canvas
    if img is None:
        return

    # 调整亮度
    img_np = np.array(img).astype(float)
    scale = brightness_scale.get()
    img_np = img_np * scale
    img_np = np.clip(img_np, 0, 255)

    img_bright = Image.fromarray(img_np.astype(np.uint8))

    # 调整对比度
    img_bright_np = cv2.cvtColor(np.array(img_bright), cv2.COLOR_RGB2GRAY)
    limit = contrast_scale.get()
    clahe = cv2.createCLAHE(clipLimit=limit, tileGridSize=(8, 8))
    img_clahe_np = clahe.apply(img_bright_np)
    img_clahe_pil = Image.fromarray(img_clahe_np)

    # 更新图片
    img_tk = ImageTk.PhotoImage(img_clahe_pil)
    image_label.config(image=img_tk)

    # 更新直方图
    fig.clear()
    plt.hist(img_clahe_np.ravel(), bins=256, range=(0, 256), color='gray', alpha=0.7)
    plt.xlabel('Pixel range: 0~255')
    plt.ylabel('Pixel count')
    canvas.draw()

# 初始化全局变量
img = None
img_tk = None
canvas = None

# 创建主窗口
root = tk.Tk()

# 创建载入图片按钮
load_button = tk.Button(root, text="Load Image", command=load_image)
load_button.pack()

# 创建图片显示标签
image_label = tk.Label(root)
image_label.pack()

# 创建亮度调节滑块
brightness_scale = tk.Scale(root, from_=0.1, to=3.0, resolution=0.1, label="亮度", orient="horizontal", command=lambda x: update_image())
brightness_scale.set(1.0)
brightness_scale.pack()

# 创建对比度调节滑块
contrast_scale = tk.Scale(root, from_=1.0, to=10.0, resolution=1.0, label="CLAHE clipLimit", orient="horizontal", command=lambda x: update_image())
contrast_scale.set(1.0)
contrast_scale.pack()

# 创建直方图绘图区
fig = plt.figure(figsize=(4, 2))
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

# 启动主循环
root.mainloop()